#include "page2_widget.h"
#include "user/welcomewidget.h"
#include "tuya_iot.h"

#define UPDATE_TIMER_INTERVAL    50
Page2_Widget::Page2_Widget(WelcomeWidget *widget)
{
    this->welcomewidget = widget;
    welcome_ui = this->welcomewidget->ui;

    m_temp_sensor = nullptr;
    m_light_sensor = nullptr;

    m_temp_sensor = new Temp_Humi();
    m_light_sensor = new Brightness();

    if((m_temp_sensor != nullptr) && (m_light_sensor != nullptr))
    {
        update_timer = new QTimer(this);
        update_timer->setInterval(UPDATE_TIMER_INTERVAL);//
        connect(update_timer, SIGNAL(timeout()), this, SLOT(slot_update_value()));
        update_timer->start();//启动定时器
    }
}

Page2_Widget::~Page2_Widget()
{

}


void Page2_Widget::slot_update_value()
{
    //update temp and humi
    if(m_temp_sensor != nullptr)m_temp_sensor->aht20_read(&temp_sensor_data);

    welcome_ui->label_temp_display->setText(QString::number(temp_sensor_data.temp)+" °C");
    welcome_ui->label_humi_display->setText(QString::number(temp_sensor_data.humi)+" %");

    welcome_ui->label_temp_dis_room->setText(QString::number(temp_sensor_data.temp+1)+" °C");
    welcome_ui->label_humi_dis_room->setText(QString::number(temp_sensor_data.humi+2)+" %");

    //update brightness
    //if(m_light_sensor != nullptr)m_light_sensor->bh1726_read(&brightness_value);
    //welcome_ui->label_brightness_display->setText(QString::number(brightness_value)+" lux");

    static int count = 0;
    static int ph_value = 30;
    static int battery_percent = 1;
    count++;
    if(count*UPDATE_TIMER_INTERVAL > 5000)
    {
        count = 0;
        if(iot_data.cloud_state == CLOUD_CONNECT)
        {
            //qDebug() << ">>> update iot data >>>";
            Tuya_IoT_Kit_Qthread::tuya_iot_report_int_value((char*)DP_TEMPERATURE, (int)temp_sensor_data.temp);
            Tuya_IoT_Kit_Qthread::tuya_iot_report_int_value((char*)DP_HUMIDITY, (int)temp_sensor_data.humi);

            Tuya_IoT_Kit_Qthread::tuya_iot_report_int_value((char*)DP_PH_VALUE, (int)ph_value++);if(ph_value > 90)ph_value = 30;
            Tuya_IoT_Kit_Qthread::tuya_iot_report_int_value((char*)DP_BATTERY_PERCENTAGE, (int)battery_percent++);if(battery_percent > 100)ph_value = 1;

            Tuya_IoT_Kit_Qthread::tuya_iot_report_int_value((char*)DP_BRIGHT_VALUE, (int)brightness_value);
        }
    }
}
